import axios from 'axios'
import qs from 'qs'
import { Toast } from 'vant'
import router from '@/router'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    const method = config.method.toLowerCase()
    // 是post传递时 修改数据形式 和header
    if (method === 'post') {
      config.data = qs.stringify(config.data)
    } else if (method === 'get') {
      config.params = config.data
    }
    config.headers['content-type'] = 'application/x-www-form-urlencoded'
    return config
  },
  error => {
    const { request: { status } } = error
    const msg = getErrors(status)
    Toast.fail(msg)
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    if (Object.prototype.toString.call(res) === '[object Object]') {
      if (res.code !== 0) {
        Toast.fail(res.message)
        return Promise.reject(res || new Error('Error'))
      } else {
        return res
      }
    } else if (Object.prototype.toString.call(res) === '[object String]') {
      return res
    }
  },
  error => {
    console.log(error)
    const { response: { status } } = error
    const msg = getErrors(status)
    Toast.fail(msg)
    if (status === 404) {
      router.replace({
        name: '404'
      })
    } else {
      return Promise.reject(error)
    }
  }
)

function getErrors (code) {
  let message = '服务器错误'
  const codes = {
    403: '拒绝访问',
    404: '请求地址出错',
    408: '请求超时',
    500: '服务器内部错误',
    502: '网关错误',
    503: '服务不可用',
    504: '网关超时',
    505: 'HTTP版本不受支持'
  }
  message = codes[code] ? codes[code] : message
  return message
}

export default service
